"""
    记录用户日志
"""
from common.libs.Helper import get_current_date
import json
from flask import request,g
from common.models.log.AppAccessLog import AppAccessLog
from common.models.log.AppErrorLog import AppErrorLog
from application import app,db

class LogService():

    # 用户正常行为记录
    @staticmethod
    def addAccessLog():
        target = AppAccessLog() # 实例化数据表对象

        target.target_url = request.url # 用户请求的地址
        target.referer_url = request.referrer # 跳转源
        target.ip = request.remote_addr # 用户ip
        target.query_params = json.dumps( request.values.to_dict() ) # 用户请求的参数

        if 'current_user' in g and g.current_user is not None:
            target.uid = g.current_user.uid

        target.ua = request.headers.get("User-Agent")

        target.created_time = get_current_date()

        db.session.add(target)
        db.session.commit()

        return True



    # 用户错误记录
    @staticmethod
    def addErrorLog(content):
        target = AppErrorLog() # 实例化数据表对象

        target.target_url = request.url  # 用户请求的地址
        target.referer_url = request.referrer  # 跳转源
        target.query_params = json.dumps(request.values.to_dict())  # 用户请求的参数

        target.content = content

        target.created_time = get_current_date()

        db.session.add(target)
        db.session.commit()

        return True